package com.drinks.yiniang.ui.activity.user.wine;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.user.winelist.WineListDetailAdapter;
import com.drinks.yiniang.common.recycler.decoration.ItemSpacesDecoration;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.entity.user.wine.WineListDetailJson;
import com.drinks.yiniang.io.api.ShoppingCartApiIO;
import com.drinks.yiniang.io.api.WineListApiIO;
import com.drinks.yiniang.io.api.WishApiIO;
import com.drinks.yiniang.ui.activity.goods.GoodsDetailsActivity;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.ActivityUtils;
import com.drinks.yiniang.utils.GlideUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.image.CircleImageView;
import com.hansen.library.ui.widget.layout.AutoLineFeedLayout;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;

/**
 * 酒单详情页面
 *
 * @author han
 * @date 2019-11-01
 */
public class WineListDetailActivity extends BaseTranBarActivity implements OnNavgationBarClickListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    private final int REQ_COMMENTS_LIST_CODE = 0x01;

    //nav
    private NavigationBarLayout nav_bar_wine_list_detail;
    private BaseRecyclerView rcv_wine_list_detail;
    //header view
    //用户头像
    private CircleImageView iv_wld_avatar;
    //昵称
    private TextView tv_wld_nickname;
    //创建时间
    private TextView tv_wld_time;
    //酒单名称
    private TextView tv_wld_name;
    //点赞数
    private TextView tv_wld_like_num;
    //收藏数
    private TextView tv_wld_wish_num;
    //评论数
    private TextView tv_wld_total_comments;
    //标签
    private AutoLineFeedLayout auto_feed_wld_label;
    //一键加入购物车
    private FrameLayout fl_wld_add_to_cart;

    private WineListDetailAdapter mWineListDetailAdapter;

    //酒单id
    private String mWineListId;
    //是否收藏酒单,1-是
    private String mCollectStatus;
    //是否点赞酒单,1-是
    private String mLiekStatus;

    @Override
    protected void initView() {
        nav_bar_wine_list_detail = findViewById(R.id.nav_bar_wine_list_detail);

        rcv_wine_list_detail = findViewById(R.id.rcv_wine_list_detail);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        mWineListId = getIntent() != null ? getIntent().getStringExtra(Constants.KeyId) : null;

        initAdapter();
        getWineDetail();
    }

    private void initAdapter() {
        rcv_wine_list_detail.setLayoutManager(new LinearLayoutManager(mContext));
        rcv_wine_list_detail.addItemDecoration(ItemSpacesDecoration.getItemDPDecoration(10));

        mWineListDetailAdapter = new WineListDetailAdapter(mContext, new ArrayList<WineListDetailJson.WineListDetailGoods>());
        mWineListDetailAdapter.addHeaderView(getHeaderView());
        mWineListDetailAdapter.addHeaderView(getHeaderBtnView());
        mWineListDetailAdapter.setHeaderAndEmpty(true);
        mWineListDetailAdapter.setCommonEmpty(getLayoutInflater(), rcv_wine_list_detail);
        mWineListDetailAdapter.bindToRecyclerView(rcv_wine_list_detail);
    }

    //获取header
    private View getHeaderView() {//header_wine_list_detail_me 查看我的酒单详情的头部
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_wine_list_detail, (ViewGroup) rcv_wine_list_detail.getParent(), false);

        iv_wld_avatar = mHeaderView.findViewById(R.id.iv_wld_avatar);

        tv_wld_nickname = mHeaderView.findViewById(R.id.tv_wld_nickname);
        tv_wld_time = mHeaderView.findViewById(R.id.tv_wld_time);
        tv_wld_name = mHeaderView.findViewById(R.id.tv_wld_name);
        tv_wld_like_num = mHeaderView.findViewById(R.id.tv_wld_like_num);
        tv_wld_wish_num = mHeaderView.findViewById(R.id.tv_wld_wish_num);
        tv_wld_total_comments = mHeaderView.findViewById(R.id.tv_wld_total_comments);

        auto_feed_wld_label = mHeaderView.findViewById(R.id.auto_feed_wld_label);

        tv_wld_total_comments.setOnClickListener(this);

        return mHeaderView;
    }

    //获取header
    private View getHeaderBtnView() {
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_wine_list_detail_btn, (ViewGroup) rcv_wine_list_detail.getParent(), false);

        fl_wld_add_to_cart = mHeaderView.findViewById(R.id.fl_wld_add_to_cart);

        fl_wld_add_to_cart.setOnClickListener(this);

        return mHeaderView;
    }

    @Override
    protected void initListener() {
        nav_bar_wine_list_detail.setOnNavgationBarClickListener(this);

        tv_wld_like_num.setOnClickListener(this);
        tv_wld_wish_num.setOnClickListener(this);

        mWineListDetailAdapter.setOnItemClickListener(this);
        mWineListDetailAdapter.setOnItemChildClickListener(this);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.tv_wld_total_comments://总评论数
                Intent intent = new Intent(mContext, WineListCommentsActivity.class);
                intent.putExtra(Constants.KeyWineListId, mWineListId);
                startActivityForResult(intent, REQ_COMMENTS_LIST_CODE);
                break;
            case R.id.tv_wld_like_num://点赞
                doLike();
                break;
            case R.id.tv_wld_wish_num://收藏
                doCollect();
                break;
            case R.id.fl_wld_add_to_cart://一键加入购物车
                addAllToCart();
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_wine_list_detail;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constants.RESULT_CODE_NORMAL && requestCode == REQ_COMMENTS_LIST_CODE) {
            getWineDetail();
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        WineListDetailJson.WineListDetailGoods data = mWineListDetailAdapter.getItem(position);

        if(data != null && view.getId() == R.id.tiv_wld_goods_add_cart) addToCart(data.getId());
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        WineListDetailJson.WineListDetailGoods data = mWineListDetailAdapter.getItem(position);

        if(data == null) {
            return;
        }

        Intent intent = new Intent(mContext, GoodsDetailsActivity.class);
        intent.putExtra(Constants.KeyGoodsId, data.getId());
        startActivity(intent);
    }

    //点赞
    private void doLike() {
        if(!ActivityUtils.isLogined(this, true)) {
            return;
        }

        if (StringUtils.isEmpty(mWineListId)) {
            ToastUtils.showShort(R.string.text_community_not_exist);
            return;
        }

        showLoadingDialog();

        WishApiIO.getInstance().doWishListLike(mWineListId, new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                mLiekStatus = Constants.STATUS_GLOBAL_YES.equals(mLiekStatus) ? Constants.STATUS_GLOBAL_NO : Constants.STATUS_GLOBAL_YES;
                setLikeStatus(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //收藏
    private void doCollect() {
        if(!ActivityUtils.isLogined(this, true)) {
            return;
        }

        if (StringUtils.isEmpty(mWineListId)) {
            ToastUtils.showShort(R.string.text_community_not_exist);
            return;
        }

        showLoadingDialog();

        WishApiIO.getInstance().doWishListCollect(mWineListId, new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                mCollectStatus = Constants.STATUS_GLOBAL_YES.equals(mCollectStatus) ? Constants.STATUS_GLOBAL_NO : Constants.STATUS_GLOBAL_YES;
                setCollectStatus(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //酒单所有商品加入购物车
    private void addAllToCart() {
        if(!ActivityUtils.isLogined(this, true)) {
            return;
        }

        if (StringUtils.isEmpty(mWineListId)) {
            ToastUtils.showShort(R.string.text_wine_list_does_not_exist);
            return;
        }

        if (CommonUtils.isEmptyList(mWineListDetailAdapter.getData())) {
            ToastUtils.showShort(R.string.text_wine_list_no_goods);
            return;
        }

        showLoadingDialog();

        WineListApiIO.getInstance().addWineListGoodsToCart(mWineListId, new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                ToastUtils.showShort(R.string.text_add_to_cart_success);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void addToCart(String goodsId) {
        showLoadingDialog();

        ShoppingCartApiIO.getInstance().addToShopCart(goodsId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                ToastUtils.showShort(getString(R.string.text_add_success));
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //获取酒单详情
    private void getWineDetail() {
        if (StringUtils.isEmpty(mWineListId)) {
            ToastUtils.showShort(R.string.text_wine_list_does_not_exist);
            return;
        }

        showLoadingDialog();

        WineListApiIO.getInstance().getWineListDetail(mWineListId, new APIRequestCallback<WineListDetailJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(WineListDetailJson res) {
                if (mWineListDetailAdapter == null) {
                    return;
                }

                setWineListData(res.getData());

                if (res.getData().getGoods() == null) {
                    res.getData().setGoods(new ArrayList<WineListDetailJson.WineListDetailGoods>());
                }

                mWineListDetailAdapter.getData().clear();
                mWineListDetailAdapter.addData(res.getData().getGoods());
                mWineListDetailAdapter.loadMoreEnd();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mWineListDetailAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //设置酒单数据
    private void setWineListData(WineListDetailJson.WineListDetailData data) {
        GlideUtils.loadAvatar(mContext, iv_wld_avatar, data.getAvatar());

        mCollectStatus = data.getIs_collect();
        mLiekStatus = data.getIs_like();

        nav_bar_wine_list_detail.setNavBarTitle(data.getUsername());

        tv_wld_nickname.setText(data.getUsername());
        tv_wld_time.setText(data.getCreated_time());
        tv_wld_name.setText(data.getTitle());
        tv_wld_total_comments.setText(String.format(getString(R.string.text_total_comment_format), StringUtils.getNullEmptyConvertZero(data.getComment_count())));
        setCollectStatus(data.getCollect_count());
        setLikeStatus(data.getLike_count());
    }

    private void setCollectStatus(String num) {
        tv_wld_wish_num.setText(StringUtils.getNullEmptyConvertZero(num));

        if (Constants.STATUS_GLOBAL_YES.equals(mCollectStatus)) {//已收藏
            tv_wld_wish_num.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_community_wishlist_p, 0, 0, 0);
        } else {
            tv_wld_wish_num.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_community_wishlist_n, 0, 0, 0);
        }
    }

    private void setLikeStatus(String num) {
        tv_wld_like_num.setText(StringUtils.getNullEmptyConvertZero(num));

        if (Constants.STATUS_GLOBAL_YES.equals(mLiekStatus)) {//已点赞
            tv_wld_like_num.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_community_like_p, 0, 0, 0);
        } else {
            tv_wld_like_num.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_community_like_n, 0, 0, 0);
        }
    }
}
